<script setup>
import { ref } from 'vue'
import router from '@/router/index.js'
import { getEmailVerify, getImgVerify } from '@/api/verify.js'
import { Message } from '@arco-design/web-vue'
import { userLogin } from '@/api/user.js'
import { useUserStore } from '@/stores/index.js'
import { encrypt } from '@/utils/encryption.js'

const loginForm = ref({
  email: '',
  code: ''
})
const loginFormRef = ref()
const loginFormRules = ref({
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur'
    },
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  code: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    },
    {
      match: /^\d{6}$/,
      message: '邮箱验证码格式不正确',
      trigger: 'blur'
    }
  ]
})

const emailCodeForm = ref({
  email: '',
  code: '',
  key: ''
})
// 邮箱验证码参数
let second = ref(180); // 有效期3分钟，180秒
let totalSecond = ref(180);
let timer = ref(null);


const emailSendLoading = ref(false)
// 获取邮箱验证码
const getCode = () => {
  if (!/^\w{4}$/.test(emailCodeForm.value.code)) {
    Message.warning('请输入正确的图形验证码');
    return false;
  }
  if (!/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/.test(loginForm.value.email)) {
    Message.warning('请输入正确的邮箱');
    return false;
  }
  emailCodeForm.value = {
    email: loginForm.value.email,
    code: emailCodeForm.value.code,
    key: emailCodeForm.value.key
  };
  if (!timer.value && second.value === totalSecond.value) {
    emailSendLoading.value = true;
    getEmailVerify(emailCodeForm.value).then((res) => {
      if (res.data.code === 1) {
        Message.success('邮箱验证码已发送,注意查收');
        emailSendLoading.value = false;
        // 开启倒计时
        timer.value = setInterval(() => {
          second.value--;

          if (second.value < 1) {
            clearInterval(timer.value);
            timer.value = null;
            second.value = totalSecond.value;
          }
        }, 1000);
      }
    }).catch((err) => {
      console.log(err);
    })
      .finally(() => {
        emailSendLoading.value = false;
      });
  }
};

const base64Img = ref('')
// 获取图形验证码
const getPicCode = () => {
  getImgVerify()
    .then(res => {
      if (res.data.code === 1) {
        emailCodeForm.value.key = res.data.data.key;
        base64Img.value = res.data.data.img;
      }
    })
    .catch(err => {
      console.log(err);
    });
};
getPicCode();

const loginLoading = ref(false)
const userStore = useUserStore()
const handleSubmit = () => {
  loginFormRef.value.validate(valid => {
    if (!valid) {
      loginLoading.value = true
      const dataForm = {
        email: encrypt(loginForm.value.email),
        emailCode: loginForm.value.code
      }
      userLogin(dataForm)
        .then(res => {
          if (res.data.code === 1) {
            Message.success('登录成功');
            userStore.updateUser(res.data.data)
            router.push('/');
          }
        })
        .catch(error => {
          console.log(error)
        })
        .finally(() => {
          loginLoading.value = false
        })
    }
  });
}
</script>

<template>
  <div id="login-page">
    <div class="login-card">
      <div class="title" @click="router.push('/')">
        <h2>逐道 在线测评系统</h2>
        <h3>ZhuDao OJ</h3>
      </div>
      <div class="form">
        <a-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" :size="'large'" @submit="handleSubmit">
          <a-form-item hide-label name="email" field="email" validate-trigger="blur">
            <a-input v-model="loginForm.email" placeholder="请输入邮箱(首次登录自动注册)"/>
          </a-form-item>
          <a-form-item hide-label name="code" field="code" validate-trigger="blur">
            <a-input v-model="loginForm.code" placeholder="请输入验证码"/>
            <a-button @click="getCode" class="code-btn" :loading="emailSendLoading">
              {{ second === totalSecond? '获取邮箱验证码' : second + `秒后可重新发送` }}
            </a-button>
          </a-form-item>
          <a-form-item hide-label name="picCode">
            <a-input v-model="emailCodeForm.code" placeholder="请输入图形验证码(点击重新获取)" />
            <img v-if="base64Img" :src="'data:image/png;base64,' + base64Img" alt="图形验证码" @click="getPicCode" />
            <img v-else alt="图形验证码" src="../../assets/pic/code_fail.png" @click="getPicCode" />
          </a-form-item>
          <a-form-item hide-label>
            <a-button type="primary" long html-type="submit" :loading="loginLoading">登录</a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
#login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #f0f2f5 url("../../assets/pic/background.svg") no-repeat;
  background-size: 100% 100%;
}

.login-card {
  width: 400px;
  height: auto;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.title {
  padding: 20px;
  background: linear-gradient(90deg, #28c5fd, #0916ff);
  border-radius: 10px 10px 0 0;
  color: #fff;
  cursor: pointer;
}

.form {
  margin-top: 20px;
  padding: 20px;
}

.form .code-btn {
  width: 120px;
  height: 31px;
  border: none;
  font-size: 14px;
  color: rgb(var(--arcoblue-6));
  background-color: transparent;
}

.form img {
  width: 120px;
  height: 36px;
}

.title h3 {
  margin-top: 10px;
}
</style>
